package com.example.a13001.shoppingmalltemplate.activitys;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.animation.AlphaAnimation;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.example.a13001.shoppingmalltemplate.MainActivity;
import com.example.a13001.shoppingmalltemplate.R;
import com.example.a13001.shoppingmalltemplate.application.ShoppingMallTemplateApplication;
import com.example.a13001.shoppingmalltemplate.base.AppConstants;
import com.example.a13001.shoppingmalltemplate.base.BaseActivity;
import com.example.a13001.shoppingmalltemplate.manager.DataManager;
import com.example.a13001.shoppingmalltemplate.modle.AppConfig;
import com.example.a13001.shoppingmalltemplate.modle.CommonResult;
import com.example.a13001.shoppingmalltemplate.modle.User;
import com.example.a13001.shoppingmalltemplate.utils.MyUtils;
import com.example.a13001.shoppingmalltemplate.utils.SPUtils;
import com.example.a13001.shoppingmalltemplate.utils.Utils;
import com.example.a13001.shoppingmalltemplate.utils.db.MyDateBaseHelpr;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.UUID;

import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.PlatformActionListener;
import cn.sharesdk.framework.PlatformDb;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.tencent.qq.QQ;
import cn.sharesdk.wechat.friends.Wechat;
import rx.Observer;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;
import rx.subscriptions.CompositeSubscription;

public class SplashActivity extends BaseActivity {
    private static final int DOWNLOAD_SUCCESS = 6;
    private final int UPDATE_NO_NEED = 0;
    private final int UPDATE_CLIENT = 3;
    private final int GET_UPDATE_INFO_ERROR = 2;
    private final int DOWN_ERROR = 4;
    private static final int sleepTime = 2000;
    private long startTime;
    private static final String TAG = "SplashActivity";
    private DataManager manager;
    private CompositeSubscription mCompositeSubscription;
    private User mUser;
    private ShoppingMallTemplateApplication model;
    private CommonResult mCommonResult;
    private AppConfig mAppConfig;
    private String mImei;
    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:

                    // 判断是否是第一次开启应用
                    String isFirstOpen = (String) SPUtils.get(AppConstants.FIRST_OPEN,"true");
                    // 如果是第一次启动，则先进入功能引导页
                    if ("true".equals(isFirstOpen)) {
                        GetNetIp();
//                        getAppConfig(AppConstants.COMPANY_ID);
                        Intent intent = new Intent(SplashActivity.this, GuideActivity.class);
                        startActivity(intent);
                        finish();
                        return;
                    }else {
                        String safetyCode = MyUtils.getMetaValue(SplashActivity.this, "safetyCode");
                        String code = Utils.md5(safetyCode + Utils.getTimeStamp());
                        String timestamp = Utils.getTimeStamp();
                        String logintype = (String) SPUtils.get("logintype", "");
                        int photoId = (int) SPUtils.get(AppConstants.photoId, 0);
                        if (photoId == 0) {
                            if (!TextUtils.isEmpty(logintype)) {

                                switch (logintype) {
                                    case "phone":
                                        ShoppingMallTemplateApplication.loginType = "phone";
                                        String username = MyUtils.getUserName();
                                        String pwd = MyUtils.getUserPwd();
                                        if (!TextUtils.isEmpty(username) && !TextUtils.isEmpty(pwd)) {

                                            Log.e(TAG, "handleMessage: " + code + "==" + Utils.getTimeStamp() + "==" + username + "--" + pwd);
                                            doLogin(AppConstants.COMPANY_ID, code, Utils.getTimeStamp(), username, pwd, AppConstants.FROM_MOBILE);

                                        } else {

                                            Intent intent = new Intent(SplashActivity.this, MainActivity.class).putExtra("type", "Splash");
                                            startActivity(intent);
                                            finish();
                                        }
                                        break;
                                    case "wechat":
//                               String  openid= (String) SPUtils.get("openid","");
//                               String  nickname= (String) SPUtils.get("nickname","");
//                               String  sex= (String) SPUtils.get("sex","");
//                               String  headimgurl= (String) SPUtils.get("headimgurl","");
                                        ShoppingMallTemplateApplication.loginType = "wechat";
//                                doThirdLogin(AppConstants.COMPANY_ID,code,timestamp,AppConstants.LOGINTYPE_WECHAT,openid,nickname,sex,headimgurl);
                                        Platform wechat = ShareSDK.getPlatform(Wechat.NAME);
                                        thirdLogin(wechat);
                                        break;
                                    case "qq":
                                        ShoppingMallTemplateApplication.loginType = "qq";
//                                doThirdLogin(AppConstants.COMPANY_ID,code,timestamp,AppConstants.LOGINTYPE_WECHAT,openid,nickname,sex,headimgurl);
                                        Platform qq = ShareSDK.getPlatform(QQ.NAME);
                                        thirdLogin(qq);
                                        break;
                                }

                            } else {
                                Intent intent = new Intent(SplashActivity.this, MainActivity.class).putExtra("type", "Splash");
                                startActivity(intent);
                                finish();
                            }
                        }else{
                            //加载广告页
                            Intent intent = new Intent(SplashActivity.this, AdActivity.class);
                            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);  //注意本行的FLAG设置
                            startActivity(intent);
                            finish();//关闭引导窗体
                        }
                    }
                    break;
                case UPDATE_NO_NEED:

                    break;
                case UPDATE_CLIENT:
//                    showUpdateDialog();
                    break;
                case 134:
                    String  ipAddress = (String) msg.obj;
                    Log.e(TAG, "统计handleMessage: 33333333333333"+ipAddress );
                    getAppConfig(AppConstants.COMPANY_ID,ipAddress);

                    break;

            }
        }
    };
    private RelativeLayout rootLayout;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        model=(ShoppingMallTemplateApplication)getApplicationContext();
        //访问SQLite数据库，判断配置文件是否建立
//        Log.v("SplashActivity", "判断数据库是否存在");
//        MyDateBaseHelpr db=new MyDateBaseHelpr(SplashActivity.this);
//        if (!db.tabIsExist("ad_config")){
//            Log.v("SplashActivity", "开始建建立数据库");
//            db.createTable("ad_config");
//        }
//        Log.v("SplashActivity", "读取数据库");
//        //判断配置文件是否存
//        Cursor DbConfig=db.select("ad_config",new String[]{"status", "adSatus", "adid", "adTitle", "adImages", "adLink"},null,null,null,null,null);
//        if (DbConfig.getCount()>0){
//            DbConfig.moveToFirst();
//            model.setStatus(DbConfig.getInt(0));
//            model.setAdStatus(DbConfig.getInt(1));
//            model.setAdId(DbConfig.getInt(2));
//            model.setAdTtitle(DbConfig.getString(3));
//            model.setAdImages(DbConfig.getString(4));
//            model.setAdLink(DbConfig.getString(5));
//        }
//        DbConfig.close();
//        db.close();
        //   --------------------------------------------------

        setContentView(R.layout.activity_splash);

        manager = new DataManager(SplashActivity.this);
        mCompositeSubscription = new CompositeSubscription();
        startTime = System.currentTimeMillis();

        rootLayout = (RelativeLayout) findViewById(R.id.splash_root);

        AlphaAnimation animation1 = new AlphaAnimation(0.3f, 1.0f);
        animation1.setDuration(1500);
        rootLayout.startAnimation(animation1);
        new Thread(new Runnable() {
            public void run() {
                long costTime = System.currentTimeMillis() - startTime;
                //wait
                if (sleepTime - costTime > 0) {
                    try {
                        Thread.sleep(sleepTime - costTime);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }

            }

        }).start();
        handler.sendEmptyMessageDelayed(1,1500);
//        new Handler().postDelayed(new Runnable() {
//            @Override
//            public void run() {
//                //这里还需判断是否有需要加载的广告
//                enterHomeActivity(model.getAdStatus());
//            }
//        }, 2000);


    }
    //启动欢迎页跳转指定页面
    private void enterHomeActivity(int type){
        if (type==1){
            //加载广告页
            Intent intent = new Intent(SplashActivity.this, AdActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);  //注意本行的FLAG设置
            startActivity(intent);
            finish();//关闭引导窗体
        } else {
            //加载主界面
            Intent intent = new Intent(SplashActivity.this, MainActivity.class).putExtra("type","Splash");
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);  //注意本行的FLAG设置
            startActivity(intent);
            finish();//关闭引导窗体
        }
    }
    /**
     * 登录
     *
     * @param companyid 站点ID
     * @param code      安全校验码
     * @param timestamp 时间戳
     * @param name      会员名称，用户名/手机/邮箱
     * @param pwd       登录密码
     * @param from      来源，pc 电脑端 mobile 移动端
     */
    public void doLogin(String companyid, String code, String timestamp, String name, String pwd, String from) {
        mCompositeSubscription.add(manager.doLogin(companyid, code, timestamp, name, pwd, from)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<User>() {
                               @Override
                               public void onCompleted() {
                                   int status=mUser.getStatus();
                                   if (status>0){
                                       startActivity(new Intent(SplashActivity.this, MainActivity.class).putExtra("type","Splash"));
                                       finish();
                                   }else{
//                                       Toast.makeText(SplashActivity.this, ""+mUser.getReturnMsg(), Toast.LENGTH_SHORT).show();
                                       Intent intent = new Intent(SplashActivity.this, MainActivity.class).putExtra("type","Splash");
                                       startActivity(intent);
                                       finish();
                                   }
                               }

                               @Override
                               public void onError(Throwable e) {
                                   Log.e(TAG, "onError: "+e.toString() );
                                   Toast.makeText(SplashActivity.this, "数据请求失败", Toast.LENGTH_SHORT).show();
                               }

                               @Override
                               public void onNext(User user) {
                                   Log.e(TAG, "onNext: "+user.toString() );
                                   mUser=user;

                               }
                           }

                ));
    }
    @Override
    protected void onStop() {
        super.onStop();
        if (mCompositeSubscription.hasSubscriptions()) {
            mCompositeSubscription.unsubscribe();
        }
    }
    private void thirdLogin(Platform platform) {
        Log.e(TAG, "onComplete: "+"aaaaa");
//        if (platform.isAuthValid()) {
//            Log.e(TAG, "onComplete: "+"cccccc");
//            platform.removeAccount(true);
//            return;
//        }
        Log.e(TAG, "onComplete: "+"bbbbbb");
        platform.setPlatformActionListener(new PlatformActionListener() {

            private String sex;

            @Override
            public void onComplete(Platform platform, int i, HashMap<String, Object> hashMap) {
                Log.e(TAG, "onComplete: "+i );
                if (i == Platform.ACTION_USER_INFOR) {
                    PlatformDb platDB = platform.getDb();//获取数平台数据DB
                    //通过DB获取各种数据
                    platDB.getToken();
                    platDB.getUserGender();
                    String icon = platDB.getUserIcon();
                    String profit = platDB.getUserId();
                    String nickname = platDB.getUserName();
                    String openid = platDB.getUserId();
                    String gender=platDB.getUserGender();
                    Iterator ite =hashMap.entrySet().iterator();
                    if("m".equals(gender)){
                        sex="1";
                    } else {
                        sex="2";
                    }

                    Log.e(TAG, "onComplete: "+icon+"profit="+profit+"nickname="+nickname+"openid="+openid+"gender="+gender+"sex="+sex);
                    String safetyCode = MyUtils.getMetaValue(SplashActivity.this, "safetyCode");
                    String code= Utils.md5(safetyCode+Utils.getTimeStamp());
                    doThirdLogin(AppConstants.COMPANY_ID,code,Utils.getTimeStamp(),AppConstants.LOGINTYPE_WECHAT,openid,nickname,sex,icon,AppConstants.androidos,MyUtils.getImei(),platform);
//                    isThirdLogin(icon, profit, nickname);
                }
            }

            @Override
            public void onError(Platform platform, int i, Throwable throwable) {
                Log.e("aaa",
                        "(LoginActivity.java:159)" + "onError");
            }

            @Override
            public void onCancel(Platform platform, int i) {
                Log.e("aaa",
                        "(LoginActivity.java:165)" + "onCancel");
            }
        });
        platform.showUser(null);
    }
    /**
     * 第三方登录
     * @param companyid   站点ID
     * @param code        安全校验码
     * @param timestamp   时间戳
     * @param type        qqlogin QQ登录， wxlogin 微信登录，sinalogin 新浪微博登录
     * @param openid      第三方登录用户唯一值
     * @param nickname    会员昵称
     * @param sex          会员性别，1 男，2 女
     * @param headimgurl   头像地址
     * @param platform
     * @return
     */
    public void doThirdLogin(String companyid, String code, String timestamp, String type, String openid, String nickname, String sex, String headimgurl,String appos,String appkey, final Platform platform) {
        mCompositeSubscription.add(manager.doThirdLogin(companyid,code,timestamp,type,openid,nickname,sex,headimgurl,appos,appkey)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<User>() {
                               @Override
                               public void onCompleted() {
                                   Log.e(TAG, "onCompleted: "+mUser.toString());
                                   int status=mUser.getStatus();
                                   if (status>0){
                                       if ("QQ".equals(platform.getName())){
                                           ShoppingMallTemplateApplication.loginType="qq";
                                       }else{
                                           ShoppingMallTemplateApplication.loginType="wechat";
                                       }

                                       startActivity(new Intent(SplashActivity.this, MainActivity.class).putExtra("type","Splash"));
                                       finish();
                                   }else{
                                       Toast.makeText(SplashActivity.this, ""+mUser.getReturnMsg(), Toast.LENGTH_SHORT).show();
                                   }
                               }

                               @Override
                               public void onError(Throwable e) {
                                   Log.e(TAG, "onError: "+e.toString() );
                                   Toast.makeText(SplashActivity.this, "数据请求失败", Toast.LENGTH_SHORT).show();
                               }

                               @Override
                               public void onNext(User user) {
                                   Log.e(TAG, "onNext: "+user.toString() );
                                   mUser=user;

                               }
                           }

                ));
    }
    /**
     *
     */
    private void getAppTongJI(String companyid, String code, String timestamp,String appos,String appkey,String appipaddress) {
        mCompositeSubscription.add(manager.getAppTongji(companyid,code,timestamp,appos,appkey,appipaddress)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<CommonResult>() {
                               @Override
                               public void onCompleted() {
                                   int status=mCommonResult.getStatus();
                                   if (status>0){

                                   }else{
//
                                   }
                               }

                               @Override
                               public void onError(Throwable e) {
                                   Log.e(TAG, "onError: "+e.toString() );
                                   Toast.makeText(SplashActivity.this, "数据请求失败", Toast.LENGTH_SHORT).show();
                               }

                               @Override
                               public void onNext(CommonResult commonResult) {
                                   Log.e(TAG, "onNext1111: "+commonResult.toString() );
                                   mCommonResult=commonResult;

                               }
                           }

                ));
    }
    public void getAppConfig(String companyid, final String ipaddress ) {

        mCompositeSubscription.add(manager.getAppConfig(companyid)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<AppConfig>() {
                    @Override
                    public void onCompleted() {
                        Log.e(TAG, "onCompleted: app配置"+mAppConfig.toString() );
                        int status=mAppConfig.getStatus();
                        if (status>0){
                            String appTongji = mAppConfig.getAppTongji();//0不开启   1开启
                            if ("1".equals(appTongji)){
                                String safetyCode = MyUtils.getMetaValue(SplashActivity.this, "safetyCode");
                                String code= Utils.md5(safetyCode+Utils.getTimeStamp());
                                String timestamp= Utils.getTimeStamp();
                                Log.e(TAG, "handleMessage: 123"+mImei );
                                if (TextUtils.isEmpty(mImei)){
                                    UUID uuid = UUID.randomUUID();
                                    mImei=uuid.toString();
                                }
//                                String ipAddress = MyUtils.getIPAddress(SplashActivity.this);
                                MyUtils.putSpuString(AppConstants.imei,mImei);
                                getAppTongJI(AppConstants.COMPANY_ID,code,timestamp,AppConstants.androidos,mImei,ipaddress);
                                Log.e(TAG, "handleMessage: "+code+"===timestamp=="+timestamp+"==mImei==="+mImei+"===ipAddress=="+ ipaddress);
                            }
                        }else{

                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        Toast.makeText(SplashActivity.this, ""+"请求失败"+e.toString(), Toast.LENGTH_SHORT).show();

                    }

                    @Override
                    public void onNext(AppConfig appConfig) {
                        mAppConfig=appConfig;
                    }
                }));
    }
    private void initDeviceID() {
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(SplashActivity.this, new String[]{Manifest.permission.READ_PHONE_STATE}, 11);
        }else {
            TelephonyManager telephonyManager = (TelephonyManager) this.getSystemService(this.TELEPHONY_SERVICE);
            String imei = telephonyManager.getDeviceId();
            mImei = imei;
        }
    }
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode==11){
            for (int i = 0; i < permissions.length; i++) {
                if (permissions[i].equals(Manifest.permission.READ_PHONE_STATE)) {
                    if (grantResults[i]!=-1){
                        initDeviceID();
                    }
                }
            }
        }
    }
    /**
     * 获取外网IP地址
     * @return
     */
    public void GetNetIp() {
        new Thread(){
            @Override
            public void run() {
                String line = "";
                URL infoUrl = null;
                InputStream inStream = null;
                try {
                    infoUrl = new URL("http://pv.sohu.com/cityjson?ie=utf-8");
                    URLConnection connection = infoUrl.openConnection();
                    HttpURLConnection httpConnection = (HttpURLConnection) connection;
                    int responseCode = httpConnection.getResponseCode();
                    if (responseCode == HttpURLConnection.HTTP_OK) {
                        inStream = httpConnection.getInputStream();
                        BufferedReader reader = new BufferedReader(new InputStreamReader(inStream, "utf-8"));
                        StringBuilder strber = new StringBuilder();
                        while ((line = reader.readLine()) != null)
                            strber.append(line + "\n");
                        inStream.close();
                        // 从反馈的结果中提取出IP地址
                        int start = strber.indexOf("{");
                        int end = strber.indexOf("}");
                        String json = strber.substring(start, end + 1);
                        if (json != null) {
                            try {
                                JSONObject jsonObject = new JSONObject(json);
                                line = jsonObject.optString("cip");
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                        Message msg = new Message();
                        msg.what = 134;
                        msg.obj = line;
                        //向主线程发送消息
                        handler.sendMessage(msg);
                    }
                } catch (MalformedURLException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }.start();
    }
}
